package dcpb.re.enc;

import java.io.IOException;
import java.math.BigInteger;
import java.util.List;
import java.util.Map;
import java.util.AbstractMap.SimpleEntry;
import java.util.LinkedList;

import it.unisa.dia.gas.jpbc.Element;
import it.unisa.dia.gas.plaf.jpbc.field.curve.CurveElement;

public class Bob {
	private PubParams p;
	ProxyReEncrypt  d=new ProxyReEncrypt ();
	int t;	
	byte[] c1;
	Element c21;
	 SimpleEntry<List<Element>,List<Element>> xsAndYs;
	 
	 Element id,sk1,sk2;
	 byte[] encryptedMessage;
	public Bob(PubParams p,int t,Fabric f) {
		this.p=p;
		this.t=t;		
		Map m=f.KeyGen();
		id=(Element) m.get("ID");
		sk1=(Element) m.get("sk_1");
		sk2=(Element) m.get("sk_2");
	}
	public void dec2(PubParams p,Map c,Element A) {
		CurveElement  sk_r=(CurveElement) sk2.duplicate().mulZn(p.one.duplicate().div(A.duplicate()));
		Element temp=p.pairing.pairing(p.G1.newElementFromBytes((byte[])c.get("c41")), sk_r);
		Element temp2=p.pairing.pairing(sk1, (Element)c.get("c6"));
		byte[] m=p.xor((byte[])c.get("c3"),temp.mul(temp2).toBytes() );
		//System.out.println("DEC2-message:"+new BigInteger(m).toString());
	}
	public void getRekey(List<Proxy> p) {
		List<Element> xs=new LinkedList(),ys=new LinkedList();
		Map c = null;
		for(Proxy pro:p) {
			c=pro.getC();
			xs.add((Element) c.get("x"));
			ys.add((Element) c.get("c31"));
		}
		this.xsAndYs=new SimpleEntry<List<Element>,List<Element>>(xs,ys);
		this.c1=(byte[]) c.get("c1");
		this.c21=(Element) c.get("c21");
	}
	public void getEncryptedMessage(){
		try {
			this.encryptedMessage=d.readFile("./data/encryptedMessage");
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	public void dec(Element A) {
		
		byte[] m2=d.Dec2(p,t,c1,c21,xsAndYs,new SimpleEntry<>(sk1,sk2),A);
	   System.out.println("DEC2-message:"+new BigInteger(m2).toString());
	   try {
		  String  message=new String(d.decrypt(encryptedMessage, new BigInteger(m2).toByteArray()));
		   //System.out.println(message);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	

}
